package com.sw.study.presisence.config;

import com.sw.study.common.exception.ExceptionConstants;
import com.sw.study.common.exception.sql.SqlMapConfigException;
import com.sw.study.presisence.pojo.Configuration;
import com.sw.study.presisence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created by sw on 2020/3/25.
 */
public class XMLMapperBuilder {
    private Configuration configuration;
    private List<String> sqlTypeList= Arrays.asList("select","update","delete","insert","SELECT","UPDATE","DELETE","INSERT");

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration=configuration;
    }


    /**
     *
     * @param inputStream
     */
    public void pareMapperXml(InputStream inputStream) throws DocumentException {
        Document mapperDocument = new SAXReader().read(inputStream);
        Element rootElement = mapperDocument.getRootElement();
        /**
         * 所有子节点 包含 udpate delete select
         */
        List<Element> sqlElements=rootElement.elements();
        String nameSpace=rootElement.attributeValue("namespace");
        MappedStatement mappedStatement=null;
        for (Element e:sqlElements){

            String sqlType= e.getQName().getName();
            if(!sqlTypeList.contains(sqlType)){
                throw  new SqlMapConfigException(ExceptionConstants.SQLMAPCONFIG,"unknow sql type:"+sqlType);
            }
            String sqlId=e.attributeValue("id");
            String paramType=e.attributeValue("paramType");
            String resultType=e.attributeValue("resultType");
            String sqlText=e.getTextTrim();
            mappedStatement=new MappedStatement();
            mappedStatement.setId(sqlId);
            mappedStatement.setParamterType(paramType);
            mappedStatement.setResutType(resultType);
            mappedStatement.setSql(sqlText);
            String sqlKey=nameSpace+"."+sqlId;
            configuration.getMappedStatementMap().put(sqlKey,mappedStatement);
        }
    }
}